# coding:utf-8 ^_^
# @Date   :
# @desc   : 进行分词绘图

from wordcloud import WordCloud
from PIL import Image
import numpy
import os


class FenciImg(object):

    def __init__(self, imagepath, imgname, fontcolormap='Set2'):
        self.imagepath = imagepath  # 背景图路径
        self.imgname = imgname      # 生成图片名称
        self.font_colormap = fontcolormap   # 图片中字体颜色

        self.perPath = os.getcwd()  # 项目路径
        self.fontpath = os.path.join(self.perPath, 'font', 'msyh.ttf')  # 字体路径，微软雅黑

    def wcd_conf(self):
        ''' 处理背景图片 '''
        try:
            global mask
            # 处理背景图片
            mask = numpy.array(Image.open(self.imagepath))
            print('背景图处理完成...')
        except Exception as e:
            print("ERROR：加载背景图失败[{}]，【{}】".format(self.imagepath, e))
        try:
            wcd = WordCloud(
                font_path=self.fontpath,  # 字体路径
                mask=mask,  # 指定词云形状，默认为长方形
                width=400, height=200,  # 词云的宽度和高度
                min_font_size=4, max_font_size=None,  # 词云中字体的最小字号
                ranks_only=None, prefer_horizontal=.9,
                max_words=200,  # 词云显示的最大单词数量
                font_step=1,  # 字号间隔
                # stopwords=None,  # 词云的排除词列表，即不显示的单词列表
                background_color='white',  # 指定词云图片的背景颜色，默认为黑色
                repeat=False,  # 重复词
                colormap=self.font_colormap,  # 词的字体颜色
                # contour_width=0.1,  # 图片边框效果
                # contour_color='red',
                )
            return wcd
        except Exception as e:
            print("ERROR: WordCloud 配置错误！", e)

    def fenci_to_image(self):
        '''    生成词云图     '''
        wcd = self.wcd_conf()
        # 分词
        try:
            with open(os.path.join(self.perPath, "处理后的分词.txt"), 'r', encoding='utf-8') as f:
                global string
                string = f.read()
            print("处理分词完成...")
        except Exception as e:
            print("ERROR：读取[处理后的分词.txt]分词文件失败，【{}】".format(e))

        if len(string) == 0:  # 判断文件为空情况
            print('ERROR： [处理后的分词.txt]文件内容为空!')
            return None

        try:   # 生成词云图
            wcd.generate(string)
        except Exception as e:
            print("ERROR：词云图生成失败 【{}】".format(e))

        try:  # 删除 处理后的分词.txt 文件
            os.remove(os.path.join(self.perPath, "处理后的分词.txt"))
            print("[处理后的分词.txt]文件删除成功...")
        except Exception as e:
            print('ERROR：[处理后的分词.txt]文件删除失败！', e)

        try:  # 判断名称是否带后缀
            if len(self.imgname.split('.')) == 1:
                name = self.imgname + '.png'
                wcd.to_file(name)
                print('[{}]词云图生成成功！'.format(name))
                return 'ok'
            else:   # 保存图片
                wcd.to_file(self.imgname)
                print('[{}]词云图生成成功！'.format(self.imgname))
                return 'ok'
        except Exception as e:
            print("ERROR：[{}]图片保存失败 【{}】".format(self.imgname, e))


if __name__ == '__main__':
    img = r"C:\Users\wangxin2_m\Desktop\niao.jpg"
    fc = FenciImg(img, 'aaaa.png')
    fc.fenci_to_image()
